﻿//-----------------------------------------------------------------------
// <copyright file="Login.aspx.cs" company="HCL">
//     Copyright (c) HCL Technologies.  All rights reserved.
// </copyright>
// <summary>
// Class for the user login validation
// </summary>
//-----------------------------------------------------------------------

namespace HCLT.Practice.WindowsAzure.Solution.STSAuthentication
{
    using System;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Microsoft.IdentityModel.Protocols.WSFederation.Metadata;

    /// <summary>
    /// This class will present the login dialogue 
    /// validate the user using network credentials
    /// </summary>
    public partial class Login : Page
    {
        /// <summary>
        /// Return url name
        /// </summary>
        private const string ReturnUrlQueryString = "ReturnUrl";

        /// <summary>
        /// page load event in page life cycle
        /// </summary>
        /// <param name="sender">sender argument</param>
        /// <param name="e">event agrument</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            lblMessage.Visible = false;
        }

        /// <summary>
        /// method to validate the user credentials from network active directory services
        /// </summary>
        /// <param name="sender">sender argument</param>
        /// <param name="e">event agguments</param>
        protected void BtnSubmit_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtUserName.Text) && !string.IsNullOrEmpty(txtPassword.Text))
            {
                if (Request.QueryString[Login.ReturnUrlQueryString] != null)
                {
                    CustomTokenValidation tokenValidator = new CustomTokenValidation();
                    if (tokenValidator.ValidateUserIdentity(txtUserName.Text, txtPassword.Text))
                    {
                        FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, false);
                    }
                    else
                    {
                        lblMessage.Visible = true;
                        lblMessage.Text = "Invalid username or password .";
                    }
                }
                else
                {
                    FormsAuthentication.SetAuthCookie(txtUserName.Text, false);
                    Response.Redirect("Default.aspx");
                }
            }
        }
    }
}